package com.xc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.Constants;
import com.google.common.collect.Lists;
import com.xc.common.Const;
import com.xc.common.ServerResponse;
import com.xc.dao.AgentUserMapper;
import com.xc.pojo.AgentUser;
import com.xc.pojo.SiteInfo;
import com.xc.service.IAgentUserService;
import com.xc.service.ISiteInfoService;
import com.xc.utils.KeyUtils;
import com.xc.utils.PropertiesUtil;
import com.xc.utils.redis.CookieUtils;
import com.xc.utils.redis.JsonUtil;
import com.xc.utils.redis.RedisShardedPoolUtils;
import com.xc.vo.agent.AgentInfoVO;
import com.xc.vo.agent.AgentSecondInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author mipha
 * @version 1.0
 * @date 2019/2/16 2:52 PM
 */
@Service("iAgentUserService")
@Slf4j
public class AgentUserServiceImpl implements IAgentUserService  {

    @Autowired
    AgentUserMapper agentUserMapper;
    @Autowired
    ISiteInfoService iSiteInfoService;


    @Override
    public AgentUser getCurrentAgent(HttpServletRequest request) {
        String loginToken = CookieUtils
                .readLoginToken(request, PropertiesUtil.getProperty("agent.cookie.name"));
        String agentJson = RedisShardedPoolUtils.get(loginToken);
        AgentUser agentUser = JsonUtil.string2Obj(agentJson , AgentUser.class);
        return agentUserMapper.selectByPrimaryKey(agentUser.getId());
    }

    @Override
    public AgentUser findByCode(String agentCode) {
        return agentUserMapper.findByCode(agentCode);
    }

    @Override
    public ServerResponse login(String agentPhone, String agentPwd
            , String verifyCode, HttpServletRequest request) {

        if(StringUtils.isBlank(verifyCode)){
            return ServerResponse.createByErrorMsg("验证码不能为空");
        }
        String original = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        log.info("代理登陆，session code = {} , 提交code = {}",original,verifyCode);
        if (!verifyCode.equalsIgnoreCase(original)) {
            return ServerResponse.createByErrorMsg("验证码错误");
        }

        if(StringUtils.isBlank(agentPhone) || StringUtils.isBlank(agentPwd)){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        AgentUser agentUser = agentUserMapper.login(agentPhone,agentPwd);
        if(agentUser == null){
            return ServerResponse.createByErrorMsg("用户密码不正确");
        }

        if(agentUser.getIsLock() == Const.AgentUserLockStatus.lock){
            return ServerResponse.createByErrorMsg("登陆失败，您的账号已被锁定！");
        }

        return ServerResponse.createBySuccess(agentUser);
    }

    @Override
    public ServerResponse getAgentInfo(HttpServletRequest request) {
        String host = "";
        ServerResponse serverResponse = iSiteInfoService.getInfo();
        if(serverResponse.isSuccess()){
            SiteInfo siteInfo = (SiteInfo)serverResponse.getData();
            if(StringUtils.isBlank(siteInfo.getSiteHost())
                    ){
                return ServerResponse.createByErrorMsg("info host未设置");
            }else{
                host = siteInfo.getSiteHost();
            }
        }

        String loginToken = CookieUtils
                .readLoginToken(request, PropertiesUtil.getProperty("agent.cookie.name"));
        String agentJson = RedisShardedPoolUtils.get(loginToken);
        AgentUser agentUser = JsonUtil.string2Obj(agentJson , AgentUser.class);
        AgentUser dbuser = agentUserMapper.selectByPrimaryKey(agentUser.getId());

        AgentInfoVO agentInfoVO = assembleAgentInfoVO(dbuser,host);
        return ServerResponse.createBySuccess(agentInfoVO);
    }

    @Override
    public ServerResponse updatePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        if(StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        AgentUser agentUser = getCurrentAgent(request);
        if(!oldPwd.equals(agentUser.getAgentPwd())){
            return ServerResponse.createByErrorMsg("密码错误");
        }

        agentUser.setAgentPwd(newPwd);
        int updateCount = agentUserMapper.updateByPrimaryKeySelective(agentUser);

        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }

    }

    @Override
    public ServerResponse addAgentUser(String agentName, String agentPwd, String agentRealName, String agentPhone, HttpServletRequest request) {
        if(StringUtils.isBlank(agentName) ||
                StringUtils.isBlank(agentPwd) ||
                StringUtils.isBlank(agentRealName) ||
                StringUtils.isBlank(agentPhone)
                ){
            return ServerResponse.createByErrorMsg("添加失败，参数不能为空");
        }
        //  查询该agent是否存在    agentname
        AgentUser dbuser = agentUserMapper.findByName(agentName);
        if(dbuser != null){
            return ServerResponse.createByErrorMsg("添加失败，代理名已存在");
        }
        //  查询手机号是否存在
        AgentUser dbuser2 = agentUserMapper.findByPhone(agentPhone);
        if(dbuser2 != null){
            return ServerResponse.createByErrorMsg("添加失败，手机号已存在");
        }

        AgentUser agentUser = new AgentUser();
        agentUser.setAgentName(agentName);
        agentUser.setAgentPwd(agentPwd);
        agentUser.setAgentCode(KeyUtils.getAgentUniqueKey());
        agentUser.setAgentRealName(agentRealName);
        agentUser.setAgentPhone(agentPhone);
        agentUser.setAddTime(new Date());
        agentUser.setIsLock(Const.AgentUserLockStatus.zhengchang);

        //  只能开设一级代理，默认上级都是自己
        AgentUser currentAgent = getCurrentAgent(request);

        agentUser.setParentId(currentAgent.getId());
        agentUser.setParentName(currentAgent.getAgentName());

        int insertCount = 0;
        try {
            insertCount = agentUserMapper.insert(agentUser);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(insertCount > 0){
            return ServerResponse.createBySuccessMsg("保存代理用户成功");
        }else{
            return ServerResponse.createByErrorMsg("添加失败，请重试");
        }
    }

    @Override
    public ServerResponse getSecondAgent(HttpServletRequest request) {
        AgentUser agentUser = getCurrentAgent(request);
        List<AgentUser> agentUsers = agentUserMapper.getSecondAgent(agentUser.getId());

        List<AgentSecondInfoVO> agentSecondInfoVOS = Lists.newArrayList();
        for (AgentUser agentUser1 : agentUsers){
            AgentSecondInfoVO agentSecondInfoVO = assembleAgentSecondInfoVO(agentUser1);
            agentSecondInfoVOS.add(agentSecondInfoVO);
        }

        return ServerResponse.createBySuccess(agentSecondInfoVOS);
    }

    @Override
    public ServerResponse<PageInfo> listByAdmin(String realName, String phone
            , int pageNum, int pageSize, HttpServletRequest request) {
        PageHelper.startPage(pageNum,pageSize);

        List<AgentUser> agentUsers = agentUserMapper.listByAdmin(realName,phone);
        PageInfo pageInfo = new PageInfo(agentUsers);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse add(AgentUser agentUser) {
        if(StringUtils.isBlank(agentUser.getAgentName())
                || StringUtils.isBlank(agentUser.getAgentPhone())
                || StringUtils.isBlank(agentUser.getAgentRealName())
                || StringUtils.isBlank(agentUser.getAgentPwd())
                ){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        //  查询手机号是否已经注册
        AgentUser pAgent = agentUserMapper.findByPhone(agentUser.getAgentPhone());
        if(pAgent != null){
            return ServerResponse.createByErrorMsg("手机号已存在");
        }
        //  查询代理名是否已经存在
        AgentUser nameAgent = agentUserMapper.findByName(agentUser.getAgentName());
        if(nameAgent != null){
            return ServerResponse.createByErrorMsg("代理名已存在");
        }

        AgentUser dbAgent = new AgentUser();
        dbAgent.setAgentName(agentUser.getAgentName());
        dbAgent.setAgentPwd(agentUser.getAgentPwd());
        dbAgent.setAgentPhone(agentUser.getAgentPhone());
        dbAgent.setAgentRealName(agentUser.getAgentRealName());
        dbAgent.setAddTime(new Date());
        dbAgent.setIsLock(Const.AgentUserLockStatus.zhengchang);

        dbAgent.setAgentCode(KeyUtils.getAgentUniqueKey());

        if(agentUser.getParentId() != null){
            AgentUser parentAgent = agentUserMapper
                    .selectByPrimaryKey(agentUser.getParentId());
            if(parentAgent != null){
                dbAgent.setParentId(parentAgent.getId());
                dbAgent.setParentName(parentAgent.getAgentName());
            }
        }

        int insertCount = agentUserMapper.insert(dbAgent);
        if(insertCount > 0){
            return ServerResponse.createBySuccessMsg("添加代理成功");
        }else{
            return ServerResponse.createByErrorMsg("添加代理失败");
        }
    }

    @Override
    public ServerResponse update(AgentUser agentUser) {
        AgentUser dbAgent = new AgentUser();

        if(StringUtils.isNotBlank(agentUser.getAgentName())){
            return ServerResponse.createByErrorMsg("公司名不能变更");
        }

        dbAgent.setId(agentUser.getId());
        if(StringUtils.isNotBlank(agentUser.getAgentPwd())){
            dbAgent.setAgentPwd(agentUser.getAgentPwd());
        }
        if(StringUtils.isNotBlank(agentUser.getAgentRealName())){
            dbAgent.setAgentRealName(agentUser.getAgentRealName());
        }
        if(StringUtils.isNotBlank(agentUser.getAgentPhone())){
            AgentUser phoneAgent = agentUserMapper.findByPhone(agentUser.getAgentPhone());
            //  查出来的手机号为空或者id是本代理就设置进去
            if(phoneAgent == null || phoneAgent.getId() == agentUser.getId()){
                dbAgent.setAgentPhone(agentUser.getAgentPhone());
            }else{
                return ServerResponse.createByErrorMsg("手机号已存在，请更换手机");
            }
        }
        if(agentUser.getIsLock() != null){
            dbAgent.setIsLock(agentUser.getIsLock());
        }

        if(agentUser.getParentId() != null){
            AgentUser parentAgent = agentUserMapper
                    .selectByPrimaryKey(agentUser.getParentId());
            if(parentAgent != null){
                dbAgent.setParentId(parentAgent.getId());
                dbAgent.setParentName(parentAgent.getAgentName());
            }
        }

        int updateCount = agentUserMapper.updateByPrimaryKeySelective(dbAgent);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("修改代理成功");
        }else{
            return ServerResponse.createByErrorMsg("修改代理失败");
        }

    }

    @Override
    public int CountAgentNum() {
        return agentUserMapper.CountAgentNum();
    }


    private AgentSecondInfoVO assembleAgentSecondInfoVO(AgentUser agentUser){
        AgentSecondInfoVO agentSecondInfoVO = new AgentSecondInfoVO();
        agentSecondInfoVO.setId(agentUser.getId());
        agentSecondInfoVO.setAgentCode(agentUser.getAgentCode());
        agentSecondInfoVO.setAgentName(agentUser.getAgentName());
        agentSecondInfoVO.setAgentPhone(agentUser.getAgentPhone());
        agentSecondInfoVO.setAgentRealName(agentUser.getAgentRealName());
        return agentSecondInfoVO;
    }

    private AgentInfoVO assembleAgentInfoVO(AgentUser agentUser,String host){
        AgentInfoVO agentInfoVO = new AgentInfoVO();

        agentInfoVO.setId(agentUser.getId());
        agentInfoVO.setAgentName(agentUser.getAgentName());
        agentInfoVO.setAgentRealName(agentUser.getAgentRealName());
        agentInfoVO.setAgentPhone(agentUser.getAgentPhone());
        agentInfoVO.setAgentCode(agentUser.getAgentCode());
        agentInfoVO.setAddTime(agentUser.getAddTime());
        agentInfoVO.setIsLock(agentUser.getIsLock());
        agentInfoVO.setParentId(agentUser.getParentId());
        agentInfoVO.setParentName(agentUser.getParentName());

        //  设置pc地址
        String pcUrl = host
                + PropertiesUtil.getProperty("site.pc.reg.url")+agentUser.getAgentCode();
        agentInfoVO.setPcUrl(pcUrl);

        //  设置m地址
        String mUrl = host
                + PropertiesUtil.getProperty("site.m.reg.url")+agentUser.getAgentCode();
        agentInfoVO.setMUrl(mUrl);

        return agentInfoVO;
    }




}
